#include "menu.h"

char* GetNodeValue(xmlNode* a_node, char *name)
{
	xmlNode *cur_node = NULL;
	for (cur_node = a_node->children; cur_node; cur_node = cur_node->next) {
		if (cur_node->type == XML_ELEMENT_NODE) {
			if (!strcmp(name,(char*) cur_node->name)) {
				return (char*) cur_node->children->content;
			}
		}
	}
	return "aa";
}

xmlNode* GetPlayNode(xmlNode * a_node,char* mode,char* difficulty)
{
	xmlNode *cur_node = NULL,*node=NULL;
	for (node=a_node->children; node; node=node->next) {
		for (cur_node = node->children; cur_node; cur_node = cur_node->next) {
			if (cur_node->type == XML_ELEMENT_NODE) {
				if (!strcmp("option", (const char*) cur_node->name)) {
					if (!strcmp("action", GetNodeValue(cur_node,"type"))) {
						if (!strcmp("play", GetNodeValue(cur_node,"action"))) {
							if (!strcmp(mode, GetNodeValue(cur_node,"mode"))) {
								if (!strcmp(difficulty, GetNodeValue(cur_node,"difficulty"))) {
									return cur_node;
								}
							}
						}
					}
				}
			}
		}
	}
	return NULL;
}

xmlNode* GetNode(xmlNode * a_node,char* name)
{
	xmlNode *cur_node = NULL;

	for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
		if (cur_node->type == XML_ELEMENT_NODE) {
			if (!strcmp("menu", (const char*) cur_node->name))
				if (!strcmp(name,(char*) cur_node->properties->children->content)) {
					return cur_node;
				}
		}
		GetNode(cur_node->children,name);
	}
	//   return NULL;
}

void SubMenu(xmlNode *elem, char *name) {
	xmlNode *root_element = NULL, *wanted_node = NULL;
	root_element = xmlDocGetRootElement(elem->doc);
	wanted_node = GetNode(root_element,name);

}

void DrawMenu(xmlNode *Nodes[10],int hover, int n, SDL_Surface *screen, SDLFont * font) {
	char * str;
	SDL_FillRect(screen,NULL,0x000000);
	//drawString(screen,font,60,10,GetNodeValue(Nodes[0],"title"));
	drawString(screen,font,30,10,GetNodeValue(Nodes[0],"title")); //modificat
	for (int i=1;i<n;i++) {
		str=GetNodeValue(Nodes[i],"title");
		if (hover == i) {
			if (!strcmp("setting",GetNodeValue(Nodes[i],"type"))) {
				drawString(screen,font,90,20+(i+1)*40,str);
				str=GetNodeValue(Nodes[i],"selected");
				drawString(screen,font,305,20+(i+1)*40,str);
			}
			else
				drawString(screen,font,95,20+(i+1)*40,str);
		}
		else {
			drawString(screen,font,90,20+(i+1)*40,str);
			if (!strcmp("setting",GetNodeValue(Nodes[i],"type"))) {
				str=GetNodeValue(Nodes[i],"selected");
				drawString(screen,font,300,20+(i+1)*40,str);
			}
		}
	}
	SDL_Flip(screen);
}

xmlNode * ShowNode(xmlNode * a_node, char * name,SDL_Surface *screen, SDLFont *font, char *titulo) {
	xmlNode *cur_node = NULL;
	xmlNode *Nodes[10];
	int x=0,y=0,n=1,done=0,i=0,mousehover=0;
	char * str;
	int mouseIndex = 0; //modificat 
	
	InitBackground(screen);
	Nodes[0]=a_node;
	//str=GetNodeValue(a_node,"title"); //modificat
	//drawString(screen,font,60,10,str); //modificat
	drawString(screen,font,30,10,titulo); //modificat
	for (cur_node = a_node->children; cur_node; cur_node = cur_node->next) {
		if (cur_node->type == XML_ELEMENT_NODE) {
			if (!strcmp("option",(char*) cur_node->name)) {
				str=GetNodeValue(cur_node,"title");
				drawString(screen,font,90,20+(n+1)*40,str);
				Nodes[n]=cur_node;
				n++;
			}
		}
	}
	SDL_Flip(screen);
	while (!done) {
		SDL_Event event;
		while (SDL_PollEvent(&event))
		{
			if (event.type == SDL_QUIT)  { return NULL; }

			if (event.type == SDL_KEYDOWN)
				if (event.key.keysym.sym == SDLK_ESCAPE) {
					if (!strcmp(name,"main")) {
						return NULL;
					}
					else {
						done = 1;
					}
				}
			mouseIndex = event.button.which; //modificat
			SDL_SelectMouse(mouseIndex); //modificat
			
			if (event.type == SDL_MOUSEBUTTONDOWN) {
				SDL_GetMouseState(&x, &y);
				mousehover=(int)(y-20)/40 - 1;
				//if (mousehover)
					return Nodes[mousehover];
			}
		}
		/*
		SDL_GetMouseState(&x, &y);
		if (x > 90 && x < 300 && y > 60 && y < 20+(n+1)*40) {
			i=(int)(y-20)/40 - 1;
			if (i != mousehover) {
				DrawMenu(Nodes,i,n,screen,font);
			}
			mousehover=i;
		}
		else {
			if (mousehover)
				DrawMenu(Nodes,0,n,screen,font);
			mousehover=0;
		}
		 */
		SDL_Delay(25);
	}
	return (a_node->parent);
}

optionsPtr ParseNode(xmlNode* cur) {
	//optionsPtr ret = NULL;
	//ret = (optionsPtr) malloc(sizeof(options));
	options * ret = NULL;
	ret = (options*)malloc(sizeof(struct options));
	if (ret == NULL) {\
		fprintf(stderr,"out of memory\n");
		return(NULL);
	}
	memset(ret, 0, sizeof(options));
	cur=cur->children;
	ret->type = "";
	ret->action = "";
	ret->submenu = "NUUUUULL";
	ret->mode = "";
	ret->difficulty = ""; 
	ret->ipclient = ""; //modificat
	ret->servpuerto = ""; //modificat
	ret->clientpuerto = ""; //modificat
	while (cur != NULL) {
		if ((!strcmp((char *)cur->name, "type")))
			ret->type = (char *) cur->children->content;
		if ((!strcmp((char *)cur->name, "submenu")))
			ret->submenu = (char *) cur->children->content;
		if ((!strcmp((char *)cur->name, "action")))
			ret->action = (char *) cur->children->content;
		if ((!strcmp((char *)cur->name, "mode")))
			ret->mode = (char *) cur->children->content;
		if ((!strcmp((char *)cur->name, "difficulty")))
			ret->difficulty = (char *) cur->children->content;
		if ((!strcmp((char *)cur->name, "ipclient")))
			ret->ipclient = (char *) cur->children->content; //modificat
		if ((!strcmp((char *)cur->name, "servpuerto")))
			ret->servpuerto = (char *) cur->children->content; //modificat
		if ((!strcmp((char *)cur->name, "clientpuerto")))
			ret->clientpuerto = (char *) cur->children->content; //modificat
		cur = cur->next;
	}
	return ret;
}


int InitMenu(char *file, Game *game,Ball *balls, Paddle *paddles, Powerup *powerups, defines  def,CSpriteBase * powerup_sprite,Mix_Chunk *puk,Mix_Chunk *pluck) {	
	UDPsocket sock;
	IPaddress address,aout;
	int channel;
	int port;
	bool selected;
	optionsPtr curoptions;
	char * name;
	
	char ipserver[100] = "Host Adress:Port";
	char portserver[100] = "Enter Your Port:";
	char portclient[100] = "Enter Your Port:";
	char *pch;
	
	char ipaux[100];
	char *portaux;
	Uint16 portauxnum = 0;
	
	xmlDoc *doc = NULL;
	int init=1;
	xmlNode *root_element = NULL, *wanted_node = NULL,*Selected_node = NULL;
	doc = xmlReadFile(file, NULL, 0);
	
	int aux = 0;
	int aux2 = 0;
	int aux3 = 0;
	int aux4 = 0;
	int aux5 = 0;
	int numpunts = 0;
	int numpuntsip = 0;
	char *str;
	
	//ipserver = strdup(name);
	//strcpy(ipserver, name);
	
	if (doc == NULL) {
		printf("error: could not parse file %s\n", file);
	}
	root_element = xmlDocGetRootElement(doc);
	wanted_node = GetNode(root_element,"main");
	while (wanted_node) {
		if (!strcmp((char*)wanted_node->name,"menu")) {
			selected=1;
			str=GetNodeValue(wanted_node,"title");
			if (!strcmp(str, "IP")) {
				str = ipserver;
				printf("IP: %s\n", str);
				
			} else if (!strcmp(str, "PUERTOSERV")) {
				str = portserver;
				printf("PORT: %s\n", str);
				
			} else if (!strcmp(str, "PUERTOCLI")) {
				str = portclient;
				printf("PORT: %s\n", str);
				
			} else {
				str=GetNodeValue(wanted_node,"title");
			}
			Selected_node=ShowNode(wanted_node,name,game->GetScreen(),game->GetFont(), str);
		}
		else {
			selected=0;
			Selected_node=wanted_node;
		}
		if (!Selected_node) return 0;
		curoptions=ParseNode(Selected_node);
		if (!strcmp(curoptions->type,"action")) {
			if (!strcmp(curoptions->action,"quit")) {
				return 0;
			}
			else if (!strcmp(curoptions->mode,"server")) {
				if(SDLNet_Init()==-1) {
					printf("SDLNet_Init: %s\n", SDLNet_GetError());
					exit(2);
				}
				game->SetBegin(0);
				game->SetEnd(0);
				game->SetDifficulty(1);
				game->SetMode(1);				
				paddles[0].SetType(Net);
				paddles[1].SetType(Human);
				//paddles[1].SetControl(Keyboard); //modificat
				paddles[1].SetControl(Joystick); //modificat
				//port = GetPort(game->GetScreen(),game->GetFont(),1); //modificat
				//port = 5555; //modificat
				//portauxnum = atoi(portserver);
				//port = portauxnum;
				
				if (atoi(portserver) > 1024) { //modificat
					port = atoi(portserver);
					//printf("portserver: %i\n", atoi(portserver));
					InitBackground(game->GetScreen());
					//drawString(game->GetScreen(),game->GetFont(),60,10,"Waiting For Connection ...");
					drawString(game->GetScreen(),game->GetFont(),0,30,"Waiting For Connection..."); //modificat
					SDL_Flip(game->GetScreen());
					if (!StartServer(&sock,&address,&channel,port)) {
						GameMain(game,init,balls,paddles,powerups,def,powerup_sprite,puk,pluck,address,sock,channel,1);
					}
					SDLNet_UDP_Unbind(sock, channel);
					SDLNet_UDP_Close(sock);
				}
				SDLNet_Quit();
			}
			else if (!strcmp(curoptions->mode,"client")) {
				if(SDLNet_Init()==-1) {
					printf("SDLNet_Init: %s\n", SDLNet_GetError());
				}	
				game->SetBegin(0);
				game->SetEnd(0);
				game->SetDifficulty(1);
				game->SetMode(1);
				paddles[0].SetType(Human);
				paddles[1].SetType(Net);
				//paddles[1].SetControl(Keyboard); //modificat
				paddles[0].SetControl(Joystick); //modificat
				
				printf("portaux: %s\n", portaux);
				//portauxnum = atoi(portaux);
				printf("portauxnum: %i\n", portauxnum);
				printf("ipserver: %s\n", ipserver);
				
				pch = strtok (ipaux, ":");
				while (pch != NULL)
				{
					portaux = pch;
					pch = strtok (NULL, ":");
				}				
				
				//port = GetPort(game->GetScreen(),game->GetFont(),0); //modificat
				//port = 6666; //modificat
				//if ((strcmp(portaux, "") == 0))  printf("ahaaaa\n");

				if ((atoi(portclient) >= 1024 || atoi(portclient) == 0) && atoi(portaux)!=0 && numpuntsip==3 && atoi(portaux) >= 1024) { //modificat
					//address = GetAddress(game->GetScreen(),game->GetFont());
					//modificat
					//SDLNet_ResolveHost(&address, "192.168.1.34", 5555); //pc antonio
					//SDLNet_ResolveHost(&address, "192.168.146.2", 5555); //pc antonio
					//SDLNet_ResolveHost(&address, "192.168.1.88", 5555); //ds antonio
					//SDLNet_ResolveHost(&address, "192.168.1.99", 5555); //psp antonio
					//printf("ipaux: %s\n", ipaux);
					portauxnum = atoi(portaux);
					//printf("portaux: %i\n", portauxnum);
					SDLNet_ResolveHost(&address, ipaux, portauxnum);
					InitBackground(game->GetScreen());
					drawString(game->GetScreen(),game->GetFont(),60,10,"Connecting ...");
					SDL_Flip(game->GetScreen());
					StartClient(&sock,address,&channel,port);
					GameMain(game,init,balls,paddles,powerups,def,powerup_sprite,puk,pluck,address,sock,channel,2);
					SDLNet_UDP_Unbind(sock, channel);
					SDLNet_UDP_Close(sock);
				}
				SDLNet_Quit();
			}
			else if (!strcmp(curoptions->mode,"nds")) {
				if(SDLNet_Init()==-1) {
					printf("SDLNet_Init: %s\n", SDLNet_GetError());
				}	
				game->SetBegin(0);
				game->SetEnd(0);
				game->SetDifficulty(1);
				game->SetMode(1);
				paddles[0].SetType(Human);
				paddles[1].SetType(Net);
				//paddles[1].SetControl(Keyboard); //modificat
				paddles[0].SetControl(Joystick); //modificat
				
				//port = GetPort(game->GetScreen(),game->GetFont(),0); //modificat
				port = 6666; //modificat
				
				if (port >= 0) { 
					//address = GetAddress(game->GetScreen(),game->GetFont());
					//modificat
					SDLNet_ResolveHost(&address, "192.168.1.88", 5555); //nds antonio
					InitBackground(game->GetScreen());
					drawString(game->GetScreen(),game->GetFont(),60,10,"Connecting NDS...");
					SDL_Flip(game->GetScreen());
					StartClient(&sock,address,&channel,port);
					GameMain(game,init,balls,paddles,powerups,def,powerup_sprite,puk,pluck,address,sock,channel,2);
					SDLNet_UDP_Unbind(sock, channel);
					SDLNet_UDP_Close(sock);
				}
				SDLNet_Quit();
			}
			else if (!strcmp(curoptions->mode,"psp")) {
				if(SDLNet_Init()==-1) {
					printf("SDLNet_Init: %s\n", SDLNet_GetError());
				}	
				game->SetBegin(0);
				game->SetEnd(0);
				game->SetDifficulty(1);
				game->SetMode(1);
				paddles[0].SetType(Human);
				paddles[1].SetType(Net);
				//paddles[1].SetControl(Keyboard); //modificat
				paddles[0].SetControl(Joystick); //modificat
				
				//port = GetPort(game->GetScreen(),game->GetFont(),0); //modificat
				port = 6666; //modificat
				
				if (port >= 0) { 
					//address = GetAddress(game->GetScreen(),game->GetFont());
					//modificat
					SDLNet_ResolveHost(&address, "192.168.1.99", 5555); //psp antonio
					InitBackground(game->GetScreen());
					drawString(game->GetScreen(),game->GetFont(),60,10,"Connecting PSP...");
					SDL_Flip(game->GetScreen());
					StartClient(&sock,address,&channel,port);
					GameMain(game,init,balls,paddles,powerups,def,powerup_sprite,puk,pluck,address,sock,channel,2);
					SDLNet_UDP_Unbind(sock, channel);
					SDLNet_UDP_Close(sock);
				}
				SDLNet_Quit();
			}
			else if (!strcmp(curoptions->mode,"pc")) {
				if(SDLNet_Init()==-1) {
					printf("SDLNet_Init: %s\n", SDLNet_GetError());
				}	
				game->SetBegin(0);
				game->SetEnd(0);
				game->SetDifficulty(1);
				game->SetMode(1);
				paddles[0].SetType(Human);
				paddles[1].SetType(Net);
				//paddles[1].SetControl(Keyboard); //modificat
				paddles[0].SetControl(Joystick); //modificat
				
				//port = GetPort(game->GetScreen(),game->GetFont(),0); //modificat
				port = 6666; //modificat
				
				if (port >= 0) { 
					//address = GetAddress(game->GetScreen(),game->GetFont());
					//modificat
					SDLNet_ResolveHost(&address, "192.168.1.34", 5555); //pc antonio
					InitBackground(game->GetScreen());
					drawString(game->GetScreen(),game->GetFont(),60,10,"Connecting PC...");
					SDL_Flip(game->GetScreen());
					StartClient(&sock,address,&channel,port);
					GameMain(game,init,balls,paddles,powerups,def,powerup_sprite,puk,pluck,address,sock,channel,2);
					SDLNet_UDP_Unbind(sock, channel);
					SDLNet_UDP_Close(sock);
				}
				SDLNet_Quit();
			}
			else if (!strcmp(curoptions->action,"play")) {
				game->SetBegin(0);
				game->SetEnd(0);
				game->SetDifficulty(1);
				
				paddles[0].SetType(AI);
				paddles[1].SetType(Human);
			
				/*
				paddles[0].SetType(Human);
				paddles[1].SetType(AI);
				*/
				paddles[0].SetControl(Joystick);
				def.SetPowerups(1);
				if (!strcmp(curoptions->difficulty,"easy"))
					
					game->SetDifficulty(1);
				if (!strcmp(curoptions->difficulty,"medium"))
					game->SetDifficulty(2);
				if (!strcmp(curoptions->difficulty,"hard"))
				{
					game->SetDifficulty(3);
				}
				if (!strcmp(curoptions->mode,"regular")) {
					game->SetMode(1);
					def.SetMaxBalls(2);
				}
				else if (!strcmp(curoptions->mode,"classic")) {
					game->SetMode(1);
					def.SetPowerups(0);
					def.SetMaxBalls(1);
				}
				else if (!strcmp(curoptions->mode,"kickups")) {
					def.SetPowerups(0);
					game->SetMode(2);
					def.SetMaxBalls(2);
				}
				else if (!strcmp(curoptions->mode,"quickplay")) {
					game->SetDifficulty(rand()%3+1);
					game->SetMode(1);
				}
				else if (!strcmp(curoptions->mode,"network")) {
					game->SetMode(1);
					//paddles[0].SetType(Net); //modificat
				}
				if (selected) init=1;
				else init=0;				
				if (!GameMain(game,init,balls,paddles,powerups,def,powerup_sprite,puk,pluck,address,sock,-1,0)) {
					name="pause-menu";
					wanted_node=GetNode(root_element,name);
				}
				else {
					name="main";
					wanted_node=GetNode(root_element,name);
				}
			}
			else if (!strcmp(curoptions->action,"resume")) {
				InitBackground(game->GetScreen());
				DrawScene(game,balls,paddles,powerups,def);
				//drawString(game->GetScreen(),game->GetFont(),450-stringWidth(game->GetFont(),"Press space to continue"),200-30,"Press space to continue"); //modificat
				drawString(game->GetScreen(),game->GetFont(),0,170,"Touch screen to continue"); //modificat
				SDL_Flip(game->GetScreen());
				wanted_node=GetPlayNode(root_element,"regular","easy");
			}
		}
		else if (!strcmp(curoptions->type,"submenu")) {
			name=curoptions->submenu;
			wanted_node=GetNode(root_element,name);
		}
		else if (!strcmp(curoptions->type,"ipclient")) { //modificat
			name=curoptions->ipclient;
			if (name[0] == ':') numpunts++;
			if (name[0] == '.') numpuntsip++;
			/*
			if (numpunts == 1 && name[0] != ':' && name[0] != '.') {
				if ( name[0] == 'e') {
					if (aux > 0) {
						aux--;
					}
					portaux[aux2] = '0';
					portaux[aux2+1] = '\0';
				} else {
					portaux[aux2] = name[0];
					portaux[aux2+1] = '\0';
					aux2++;
				}
			} else if (name[0] != ':'){
				if (name[0] == 'e') {
					if (aux > 0) { 
						aux3--;
					}
					ipaux[aux3] = '0';
					ipaux[aux3+1] = '\0';
				} else {
					ipaux[aux3] = name[0];
					ipaux[aux3+1] = '\0';
					aux3++;
				}
			}
			 */

			if (name[0] == 'e') {
				if (aux > 0) {
					aux--;
					if (ipserver[aux] == ':') {
						if (numpunts > 0) {
							numpunts--;
						}
					}
					if (ipserver[aux] == '.') {
						if (numpuntsip > 0) {
							numpuntsip--;
						}
					}
				}
				//ipserver[aux] = '0';
				//ipserver[aux+1] = '\0';
				//ipaux[aux] = '0';
				//ipaux[aux+1] = '\0';
				ipserver[aux] = '\0';
				ipaux[aux] = '\0';
			} else {
				ipserver[aux] = name[0];
				ipserver[aux+1] = '\0';
				ipaux[aux] = name[0];
				ipaux[aux+1] = '\0';
				aux++;
			}
			
			//printf("name: %c\n", name[0]);
			//printf("aux: %i\n", aux);
			//printf("numpunts: %i\n", numpunts);
			//printf("ipserver: %s\n", ipserver);
			//printf("portaux: %s\n", portaux);
			//InitBackground(game->GetScreen());
			//drawString(game->GetScreen(),game->GetFont(),0,170, ipserver);
			//SDL_Flip(game->GetScreen());
			//SDL_Delay(1500);
			 wanted_node=GetNode(root_element,"ipperalclient");
			/*
			if (numpunts == 1) {
				wanted_node=GetNode(root_element,"fiipclient");
			} else {
				wanted_node=GetNode(root_element,"ipperalclient");
			}
			 */
		}
		
		else if (!strcmp(curoptions->type,"servpuerto")) { //modificat
			name=curoptions->servpuerto;
			if (name[0] == 'e') {
				if (aux4 > 0) {
					aux4--;
				}
				//portserver[aux4] = '0';
				//portserver[aux4+1] = '\0';
				portserver[aux4] = '\0';
			} else {
				portserver[aux4] = name[0];
				portserver[aux4+1] = '\0';
				aux4++;
			}
			wanted_node=GetNode(root_element,"portserver");
		}
		
		else if (!strcmp(curoptions->type,"clientpuerto")) { //modificat
			name=curoptions->clientpuerto;
			if (name[0] == 'e') {
				if (aux5 > 0) {
					aux5--;
				}
				//portclient[aux5] = '0';
				//portclient[aux5+1] = '\0';
				portclient[aux5] = '\0';
			} else {
				portclient[aux5] = name[0];
				portclient[aux5+1] = '\0';
				aux5++;
			}
			wanted_node=GetNode(root_element,"portclient");
		}
		
		else {
			//wanted_node=GetNode(root_element,"main");
			printf("name: %s", name);
			if (name != NULL) wanted_node=GetNode(root_element, name);
			else wanted_node=GetNode(root_element, "main");
		}
	}
	
	xmlFreeDoc(doc);
	xmlCleanupParser();
	
	/*
	 UDPsocket sock;
	 IPaddress address;
	 int init=1;
	 game->SetBegin(0);
	 game->SetEnd(0);
	 game->SetDifficulty(1);
	 game->SetMode(1);
	 paddles[0].SetType(AI);
	 paddles[1].SetType(Human);
	 paddles[0].SetControl(Accel);
	 paddles[1].SetControl(Accel);
	 GameMain(game,init,balls,paddles,powerups,def,powerup_sprite,puk,pluck,address,sock,-1,0);
	 */
	
	return 1;
}

